package com.jx.gocomtask;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jx.gocomtask.utils.JacksonUtil;
import com.jx.gocomtask.webservice.DTO.UserToken;
import com.jx.gocomtask.webservice.service.SystemSuperApp;
//import com.gocom.imoss.common.Exception.AuthorizedException;

//import phoenics.common.exception.StatusException;


@Configuration
class MvcConf extends WebMvcConfigurerAdapter {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(MvcConf.class);
	public static final String JSON_UTF_8 = "application/json; charset=UTF-8";
	@Resource(name="apiurl")
	String gocomeApiUrl;
	@Resource(name="defaultAppId")
	String defaultAppId;
	@Resource(name="defaultGroupAppId")
	String  defaultGroupAppId;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	SystemSuperApp systemSuperApp;
	@Override
	public void addCorsMappings(CorsRegistry  registry){
		registry.addMapping("/**")
		.allowedOrigins("*")

		//.allowCredentials(true)
		//.allowedMethods("GET,POST,OPTIONS,PUT,DELETE")
		.allowedMethods("*")
		.maxAge(3600);
	}
	public void addInterceptors(InterceptorRegistry registry) {
	      registry.addInterceptor(new HandlerInterceptorAdapter() {

	          @Override
	          public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
	                                   Object handler) throws Exception {
	        	  String wptoken=request.getParameter("token");
	        	  return isAuthory(wptoken,request,response);
	          }
	      }).addPathPatterns("/task/**","/todo/**","/schedule/**");
	  }
	private boolean isAuthory(String wptoken, HttpServletRequest request,HttpServletResponse response){
		boolean tag=false;
		String rt = restTemplate.postForObject(gocomeApiUrl + "sauth/token?"+systemSuperApp.appid_token(defaultAppId)+"&token="+wptoken,null,String.class);
		UserToken userToken=JacksonUtil.readValue(rt, UserToken.class);
		//logger.info(rt);
		if(userToken.getUserid()==null ){
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			//return null;
		}else{
			request.setAttribute("userid", userToken.getUserid());
			tag=true;
		}
		return tag;
	}
}
